package net.ytbolg.mcxa.gui;

import net.ytbolg.mcxa.gui.Main;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import net.ytbolg.mcxa.gui.Lang_and_ConfigManager.LangManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import javax.swing.JTable.*;

/**
 *
 * @author Ytong
 */
public class DownloadCenter extends javax.swing.JFrame {

    /**
     * Creates new form DownloadCenter
     */
    public DownloadCenter() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jTabbedPane2 = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        MC_Rel = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        MC_SNAP = new javax.swing.JTable();
        jScrollPane3 = new javax.swing.JScrollPane();
        MC_OLD = new javax.swing.JTable();
        jScrollPane4 = new javax.swing.JScrollPane();
        MC_ALL = new javax.swing.JTable();
        jTabbedPane3 = new javax.swing.JTabbedPane();
        jScrollPane5 = new javax.swing.JScrollPane();
        Forge_New = new javax.swing.JTable();
        jScrollPane6 = new javax.swing.JScrollPane();
        Forge_OLD = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("下载中心 双击下载");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jTabbedPane1.setName(""); // NOI18N

        MC_Rel.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "版本号", "发布时间", "版本类型"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        MC_Rel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                MC_RelMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(MC_Rel);

        jTabbedPane2.addTab("正式版", jScrollPane1);

        MC_SNAP.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "版本号", "发布时间", "版本类型"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        MC_SNAP.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                MC_SNAPMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(MC_SNAP);

        jTabbedPane2.addTab("预览版", jScrollPane2);

        MC_OLD.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "版本号", "发布时间", "版本类型"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        MC_OLD.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                MC_OLDMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(MC_OLD);

        jTabbedPane2.addTab("旧版本", jScrollPane3);

        MC_ALL.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "版本号", "发布时间", "版本类型"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        MC_ALL.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                MC_ALLMouseClicked(evt);
            }
        });
        jScrollPane4.setViewportView(MC_ALL);

        jTabbedPane2.addTab("全部", jScrollPane4);

        jTabbedPane1.addTab("MC下载", jTabbedPane2);

        Forge_New.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "MC版本", "Forge版本", "版本名", "发布时间"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        Forge_New.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                Forge_NewMouseClicked(evt);
            }
        });
        jScrollPane5.setViewportView(Forge_New);

        jTabbedPane3.addTab("新版本", jScrollPane5);

        Forge_OLD.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "MC版本", "Forge版本", "版本名", "发布时间"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        Forge_OLD.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                Forge_OLDMouseClicked(evt);
            }
        });
        jScrollPane6.setViewportView(Forge_OLD);

        jTabbedPane3.addTab("旧版本", jScrollPane6);

        jTabbedPane1.addTab("Forge下载", jTabbedPane3);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 498, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
  LoadLanguage();
        Flush();
        MC_ALL.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        MC_SNAP.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        MC_OLD.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        MC_Rel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        Forge_New.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        Forge_OLD.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
    }//GEN-LAST:event_formWindowOpened

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        Main.me.setEnabled(true);        // TODO add your handling code here:
    }//GEN-LAST:event_formWindowClosed

    private void MC_RelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_MC_RelMouseClicked
        if (evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() == 2) {
            File fol = new File(General.GameDir + General.separator + "versions" + General.separator + MC_Rel.getModel().getValueAt(MC_Rel.getSelectedRow(), 0).toString());
            if (fol.exists() && fol.isDirectory()) {
                JOptionPane.showMessageDialog(rootPane, LangManager.getStringByKey("已经在版本目录里发现了该版本！请删除后再下载！"), "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            DownloadWindow dc = new DownloadWindow();
            String selitem = MC_Rel.getModel().getValueAt(MC_Rel.getSelectedRow(), 0).toString();
            //     System.out.println(selitem);
            dc.addDownload(DownloadSrc.getMcJarDownloadURL(selitem), fol.toString() + General.separator + selitem + ".jar");
            dc.addDownload(DownloadSrc.getMcJsonDownloadURL(selitem), fol.toString() + General.separator + selitem + ".json");
            new Thread(dc).start();
            dc.setVisible(true);
        }     // TODO add your handling code here:
    }//GEN-LAST:event_MC_RelMouseClicked

    private void MC_SNAPMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_MC_SNAPMouseClicked
        JTable tb = MC_SNAP;
        if (evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() == 2) {
            File fol = new File(General.GameDir + General.separator + "versions" + General.separator + tb.getModel().getValueAt(tb.getSelectedRow(), 0).toString());
            if (fol.exists() && fol.isDirectory()) {
                JOptionPane.showMessageDialog(rootPane, LangManager.getStringByKey("已经在版本目录里发现了该版本！请删除后再下载！"), "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            DownloadWindow dc = new DownloadWindow();
            String selitem = tb.getModel().getValueAt(tb.getSelectedRow(), 0).toString();
            //     System.out.println(selitem);
            dc.addDownload(DownloadSrc.getMcJarDownloadURL(selitem), fol.toString() + General.separator + selitem + ".jar");
            dc.addDownload(DownloadSrc.getMcJsonDownloadURL(selitem), fol.toString() + General.separator + selitem + ".json");
            new Thread(dc).start();
            dc.setVisible(true);
        }         // TODO add your handling code here:
    }//GEN-LAST:event_MC_SNAPMouseClicked

    private void MC_OLDMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_MC_OLDMouseClicked
        JTable tb = MC_OLD;
        if (evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() == 2) {
            File fol = new File(General.GameDir + General.separator + "versions" + General.separator + tb.getModel().getValueAt(tb.getSelectedRow(), 0).toString());
            if (fol.exists() && fol.isDirectory()) {
                JOptionPane.showMessageDialog(rootPane, LangManager.getStringByKey("已经在版本目录里发现了该版本！请删除后再下载！"), "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            DownloadWindow dc = new DownloadWindow();
            String selitem = tb.getModel().getValueAt(tb.getSelectedRow(), 0).toString();
            //     System.out.println(selitem);
            dc.addDownload(DownloadSrc.getMcJarDownloadURL(selitem), fol.toString() + General.separator + selitem + ".jar");
            dc.addDownload(DownloadSrc.getMcJsonDownloadURL(selitem), fol.toString() + General.separator + selitem + ".json");
            new Thread(dc).start();
            dc.setVisible(true);
        }            // TODO add your handling code here:
    }//GEN-LAST:event_MC_OLDMouseClicked

    private void MC_ALLMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_MC_ALLMouseClicked
        JTable tb = MC_ALL;
        if (evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() == 2) {
            File fol = new File(General.GameDir + General.separator + "versions" + General.separator + tb.getModel().getValueAt(tb.getSelectedRow(), 0).toString());
            if (fol.exists() && fol.isDirectory()) {
                JOptionPane.showMessageDialog(rootPane, LangManager.getStringByKey("已经在版本目录里发现了该版本！请删除后再下载！"), "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            DownloadWindow dc = new DownloadWindow();
            String selitem = tb.getModel().getValueAt(tb.getSelectedRow(), 0).toString();
            //     System.out.println(selitem);
            dc.addDownload(DownloadSrc.getMcJarDownloadURL(selitem), fol.toString() + General.separator + selitem + ".jar");
            dc.addDownload(DownloadSrc.getMcJsonDownloadURL(selitem), fol.toString() + General.separator + selitem + ".json");
            new Thread(dc).start();
            dc.setVisible(true);
        }            // TODO add your handling code here:
    }//GEN-LAST:event_MC_ALLMouseClicked

    private void Forge_NewMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Forge_NewMouseClicked
        JTable tb = Forge_New;
        if (evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() == 2) {
       //     File fol = new File(General.GameDir + General.separator + "versions" + General.separator + tb.getModel().getValueAt(tb.getSelectedRow(), 0).toString());
            
            DownloadWindow dc = new DownloadWindow();
            String mc_ver = tb.getModel().getValueAt(tb.getSelectedRow(), 0).toString();
            String forge_ver = tb.getModel().getValueAt(tb.getSelectedRow(), 1).toString();
            //     System.out.println(selitem);
            dc.addDownload(DownloadSrc.getForgeURL(mc_ver, forge_ver), General.AppDir + General.separator + "forgetemp.jar");
            //     dc.addDownload(DownloadSrc.getMcJsonDownloadURL(selitem), fol.toString() + General.separator + selitem + ".json");
            dc.setIsForge(true);
            new Thread(dc).start();
            dc.setVisible(true);
        }            // TODO add your handling code here:
    }//GEN-LAST:event_Forge_NewMouseClicked

    private void Forge_OLDMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Forge_OLDMouseClicked
       JTable tb = Forge_OLD;
        if (evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() == 2) {
       //     File fol = new File(General.GameDir + General.separator + "versions" + General.separator + tb.getModel().getValueAt(tb.getSelectedRow(), 0).toString());
            
            DownloadWindow dc = new DownloadWindow();
            String mc_ver = tb.getModel().getValueAt(tb.getSelectedRow(), 0).toString();
            String forge_ver = tb.getModel().getValueAt(tb.getSelectedRow(), 1).toString();
            //     System.out.println(selitem);
            dc.addDownload(DownloadSrc.getForgeURL(mc_ver, forge_ver), General.AppDir + General.separator + "forgetemp.jar");
            //     dc.addDownload(DownloadSrc.getMcJsonDownloadURL(selitem), fol.toString() + General.separator + selitem + ".json");
            dc.setIsForge(true);
            new Thread(dc).start();
            dc.setVisible(true);
        }        // TODO add your handling code here:
    }//GEN-LAST:event_Forge_OLDMouseClicked

    /**
     * @param args the command line arguments
     */

    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JTable Forge_New;
    public javax.swing.JTable Forge_OLD;
    public javax.swing.JTable MC_ALL;
    public javax.swing.JTable MC_OLD;
    public javax.swing.JTable MC_Rel;
    public javax.swing.JTable MC_SNAP;
    public javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JScrollPane jScrollPane2;
    public javax.swing.JScrollPane jScrollPane3;
    public javax.swing.JScrollPane jScrollPane4;
    public javax.swing.JScrollPane jScrollPane5;
    public javax.swing.JScrollPane jScrollPane6;
    public javax.swing.JTabbedPane jTabbedPane1;
    public javax.swing.JTabbedPane jTabbedPane2;
    public javax.swing.JTabbedPane jTabbedPane3;
    // End of variables declaration//GEN-END:variables
void Flush() {
        FlushForge();
        FlushMC();
    }
    
    void FlushMC() {
        try {
            JSONObject mc = new JSONObject(CommonTools.URLToString(DownloadSrc.getMCListURL()));
            JSONArray arr = mc.getJSONArray("versions");
            DefaultTableModel REL = (DefaultTableModel) MC_Rel.getModel();
            DefaultTableModel SNAP = (DefaultTableModel) MC_SNAP.getModel();
            DefaultTableModel OLD = (DefaultTableModel) MC_OLD.getModel();
            DefaultTableModel ALL = (DefaultTableModel) MC_ALL.getModel();
            
            for (int i = 0; i < arr.length(); i++) {
                JSONObject jo = arr.getJSONObject(i);
                ALL.addRow(new Object[]{jo.get("id"), jo.get("releaseTime"), jo.get("type")});
                switch (jo.getString("type")) {
                    case "snapshot":
                        SNAP.addRow(new Object[]{jo.get("id"), jo.get("releaseTime"), jo.get("type")});
                        break;
                    case "release":
                        REL.addRow(new Object[]{jo.get("id"), jo.get("releaseTime"), jo.get("type")});
                        break;
                    case "old_alpha":
                        OLD.addRow(new Object[]{jo.get("id"), jo.get("releaseTime"), jo.get("type")});
                        break;
                    case "old_beta":
                        OLD.addRow(new Object[]{jo.get("id"), jo.get("releaseTime"), jo.get("type")});
                        break;
                    
                }
            }
        } catch (JSONException ex) {
            Logger.getLogger(DownloadCenter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DownloadCenter.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
    void FlushForge() {
        try {
            JSONArray List = new JSONArray(CommonTools.URLToString(DownloadSrc.getForgeListURL()));
            DefaultTableModel OLD = (DefaultTableModel) Forge_OLD.getModel();
            DefaultTableModel NEW = (DefaultTableModel) Forge_New.getModel();
            JSONArray Legacy = new JSONArray(CommonTools.URLToString(DownloadSrc.getForgeLegacyListURL()));
            for (int i = 0; i < List.length(); i++) {
                JSONObject jo = List.getJSONObject(i);
                String vername = "";
                if (jo.has("vername")) {
                    vername = jo.getString("vername");
                    
                }
                NEW.addRow(new Object[]{jo.get("mcver"), jo.get("ver"), vername, jo.get("releasetime")});
            }
            
            for (int i = 0; i < Legacy.length(); i++) {
                JSONObject jo = Legacy.getJSONObject(i);
                String vername = "";
                if (jo.has("vername")) {
                    vername = jo.getString("vername");
                    
                }
                OLD.addRow(new Object[]{jo.get("mcver"), jo.get("ver"), vername, jo.get("releasetime")});
            }
        } catch (JSONException ex) {
            Logger.getLogger(DownloadCenter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(DownloadCenter.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
    void LoadLanguage() {
        jTabbedPane1.setTitleAt(0, LangManager.getStringByKey(jTabbedPane1.getTitleAt(0)));
        jTabbedPane1.setTitleAt(1, LangManager.getStringByKey(jTabbedPane1.getTitleAt(1)));
        
        jTabbedPane2.setTitleAt(0, LangManager.getStringByKey(jTabbedPane2.getTitleAt(0)));
        jTabbedPane2.setTitleAt(1, LangManager.getStringByKey(jTabbedPane2.getTitleAt(1)));
        jTabbedPane2.setTitleAt(2, LangManager.getStringByKey(jTabbedPane2.getTitleAt(2)));
        jTabbedPane2.setTitleAt(3, LangManager.getStringByKey(jTabbedPane2.getTitleAt(3)));
        
        jTabbedPane3.setTitleAt(0, LangManager.getStringByKey(jTabbedPane3.getTitleAt(0)));
        jTabbedPane3.setTitleAt(1, LangManager.getStringByKey(jTabbedPane3.getTitleAt(1)));
        
        setTitle(LangManager.getStringByKey("下载中心 双击下载"));
//(DefaultTableColumnModel)MC_OLD.getColumnModel().
    }
}
